<template>
	<div class="container">
		<el-row :gutter="20">
			<el-col :span="6" :body-style="{padding: '0px'}">
				<el-card class="page-left" shadow="always">
					<div ref="mapChart" class="map"></div>
				</el-card>
			</el-col>
			<el-col :span="6" :body-style="{padding: '0px'}">
				<el-card class="page-right" shadow="always">
					<el-tabs v-model="activeName" style="height: 890px" @tab-click="handleClick" type="border-card">
						<el-tab-pane label="手动选择路线" name="first">
							<el-form :model="manualForm" label-width="auto" style="max-width: 600px">
								<el-form-item label="路线">
									<el-input v-model="manualForm.path" placeholder="请点击分布图标点手动更改路线" />
								</el-form-item>
								<el-form-item>
									<el-popconfirm
											confirm-button-text="是"
											cancel-button-text="否"
											:icon="InfoFilled"
											icon-color="#626AEF"
											title="确认使用手动逃生路线？"
											@confirm="submitPath()"
											@cancel="cancelEvent()"
									>
										<template #reference>
											<el-button>提交</el-button>
										</template>
									</el-popconfirm>
								</el-form-item>
							</el-form>
						</el-tab-pane>
						<el-tab-pane label="自动选择路线" name="second">
							<el-form :model="autoForm" label-width="auto" style="max-width: 600px">
								<el-form-item label="起始位置">
									<el-input v-model="autoForm.startPath" placeholder="请点击分布图标点选择起始位置" />
								</el-form-item>
								<el-form-item label="出口位置">
									<el-input v-model="autoForm.endPath" placeholder="请点击分布图标点选择出口位置"/>
								</el-form-item>
								<el-form-item>
									<el-popconfirm
											confirm-button-text="是"
											cancel-button-text="否"
											:icon="InfoFilled"
											icon-color="#626AEF"
											title="确认使用手动逃生路线？"
											@confirm="submitPath()"
											@cancel="cancelEvent()"
									>
										<template #reference>
											<el-button>提交</el-button>
										</template>
									</el-popconfirm>
								</el-form-item>
							</el-form>
						</el-tab-pane>
					</el-tabs>
				</el-card>
			</el-col>
		</el-row>
	</div>
</template>

<script setup lang="ts" name="emergencymode">
import {onMounted, reactive, ref} from "vue";
import * as echarts from "echarts";
import BanNan from "../MapJson/巴南区.json"
import ChongQing from "../MapJson/重庆市.json"
import DemoRoom from "../MapJson/map.json"
import API from "../utils/axios";
import {ElMessage} from "element-plus";
import type { TabsPaneContext } from 'element-plus';
import {InfoFilled} from "@element-plus/icons-vue";

// 发送操控指令
// 操控指令数据
const deviceIdSet  = {
	deviceNumberSet: [],
	order: '',
}
// 提交按钮触发事件
const submitPath = () => {
	if (deviceIdSet.deviceNumberSet.length != 0){
		deviceIdSet.deviceNumberSet = [];
	}
	deviceIdSet.deviceNumberSet = manualForm.path
	deviceIdSet.order = 'turn_on';
	API.post("/DeviceController/controlDevice", deviceIdSet)
			.then((res) => {
				ElMessage(res.data.data);
				ElMessage.success("更改成功！")
				if (manualForm.path.length != 0){
					manualForm.path = [];
				}
			})
			.catch((err) => {return err})
}

// 取消按钮触发事件
const cancelEvent = () => {
	ElMessage.error("已取消！")
}

const activeName = ref('first')
const handleClick = (tab: TabsPaneContext, event: Event) => {
	console.log(tab, event)
}

const manualForm = reactive({
	path:[]
})

const autoForm = ref({
	startPath:[],
	endPath:[]
})

const getColor = (securityLevel : any, workStatus : any) => {
	// 如果设备处于开启状态，则显示为开启状态紫色
	// 否则则根据参数显示不同颜色
	if (workStatus === 1){
		return '#cd99fb';   // 紫色
	}else {
		if (0 <= securityLevel && securityLevel < 20) {
			return '#5db556'; // 绿色
		} else if (securityLevel >= 20 && securityLevel < 50) {
			return '#3c69e6'; // 蓝色
		} else if (securityLevel >= 50 && securityLevel < 70) {
			return '#de9723'; // 橙色
		}else if (securityLevel >= 70){
			return '#dd0000'; // 红色
		}
	}
}

const mapChart = ref();
let myMapChart : echarts.EChartOption;
const coordinate = ref([])
onMounted(async () => {
	await closeAllDevice();
	getLightDevice();
	// 实例化Echarts
	myMapChart = echarts.init(mapChart.value, "dark");
	echarts.registerMap("Room", DemoRoom);
	const map_option = {
		title: {
			text: '设备分布图',
			left: 'center',
			top: 30,
		},
// 连续型数据不分段。
		visualMap: {
			bottom: "9%",
			right: "15%",
			type: 'continuous', // 连续型
			min: 0, // 最小值
			max: 100, // 最大值
			text: ['危险', '安全'],
			inRange: {
				color: ['#5db556', '#3c69e6', '#de9723', '#dd0000']
			},
			seriesIndex: 1,
		},
		tooltip: {
			formatter: function (params) {
				// 获取设备编号和设备名称
				let deviceName = params.data.deviceName;
				let deviceId = params.data.deviceId;
				let Temperature = params.data.Temperature;
				let	Humidity = params.data.Humidity;
				let	SmokeScope = params.data.SmokeScope;
				let securityLevel = params.data.securityLevel;
				// 自定义展示的内容
				return `设备编号: ${deviceId}<br>设备名称: ${deviceName}<br>温度:${Temperature}℃<br>湿度:${Humidity}%<br>烟雾浓度:${SmokeScope}ppm<br>危险系数:${securityLevel}`;
			},
		},
		geo: {
			tooltip: {
				show: true
			},
			map: 'Room',
			roam: false,
			itemStyle: {
				// 定义地图初始样式
				normal: {
					areaColor: '#e8e8e8', // 地图区域的颜色
					borderColor: '#000000'
				},
				// 定义鼠标悬浮时的样式
				emphasis: {
					areaColor: '#74f1de' // 鼠标悬浮时地图区域的颜色，根据需求调整
				},
			},
			label: {
				normal: {
					show: true, // 设置为true，使得地图上的区域名称始终显示
					textStyle: {
						color: '#000', // 文本颜色
						fontSize: 20 // 文本字体大小
					}
				},
				emphasis: {
					show: true,
					textStyle: {
						color: '#fff' // 鼠标悬浮时文本颜色
					}
				}
			}
		},
		series: {
			type: 'effectScatter',
			coordinateSystem: 'geo',
			geoIndex: 0,
			symbolSize: function (params: any) {
				return (params[2] / 100) * 15 + 5;
			},
			itemStyle: {
				color: function (params){
					return getColor(params.data.securityLevel,params.data.workStatus)
				}
			},
			encode: {
				tooltip: 2
			},
			data: coordinate.value
		}
	};
// 渲染数据
	myMapChart.setOption(map_option);
	// 添加点击事件监听器
	myMapChart.on('click', (params) => {
		if (params.componentType === 'series' && params.seriesType === 'effectScatter') {
			manualForm.path.map((item : any, index : number) => {
				if (item === params.data.deviceId){
					manualForm.path.splice(index, 1);
				}
			})
			manualForm.path.push(params.data.deviceId);
		}
	});
})

// 更新数据
const updateSeriesData = () => {
	const map_option = {
		series: {
			data : coordinate.value
		}
	}
	myMapChart.setOption(map_option);
};

// 关闭所有灯光设备
const closeAllDevice = () => {
  API.post("/DeviceController/offLineAllDevice")
			.then((res) => {
				ElMessage.success(res.data.data);
				console.log("关闭所有灯光")
			})
			.catch((err) => {return err})
}


// 灯光设备数据
const deviceData = ref([]);
// 获取灯光设备数据
const getLightDevice = () => {
	API.post('/DeviceController/getAllDevice')
			.then((res) => {
				const newData  = res.data.data.map((item : any) => {
					let workStatus  = '';
					if (item.deviceWorkStatus == 0){
						workStatus = '离线';
					}else{
						workStatus = '在线';
					}
					return {
						ID : item.deviceNumber,
						name: item.deviceName,
						type : item.deviceType,
						mac : item.deviceMac,
						address : item.roomName,
						workStatus : workStatus,
						note : item.deviceNote,
						onlineTime : item.deviceOnlineTime,
						deviceStatus : item.deviceStatus,
						longitude : item.deviceLongitude,
						latitude : item.deviceLatitude,
					}
				})
				deviceData.value = newData;
				deviceData.value.map((item : any) => {
					coordinate.value.push({
						value : [item.longitude,item.latitude,150],
						deviceName : item.name,
						deviceId : item.ID,
						Temperature : 0,
						Humidity : 0,
						SmokeScope : 0,
						workStatus : 0,
						securityLevel : 0
					});
				})
				updateSeriesData();
			})
			.catch((err) => {
				return err
			})
};
// 建立WebSocket连接
const ws = new WebSocket("ws://localhost:8085/webSocket");
ws.onopen = function (event){
	console.log('建立连接');
}
ws.onclose = function (event){
	console.log('连接关闭');
}
ws.onmessage= function (event){
	// 进行弹窗提醒或其他操作
	try {
		// 将接收到的 JSON 字符串转换成 JavaScript 对象
		const message = JSON.parse(event.data);
		// 设备数据处理
		coordinate.value.map((item : any) => {
			if (message.dataType == item.deviceId){
				getEnvironmentData(message);
			}
		})
	} catch (error) {
		console.error('JSON 解析出错', error);
	}
}
ws.onerror= function (){
	alert('websocket通信发生错误！')
};
const getEnvironmentData = (message : any) => {
	// 获取更新数据
	const socketData = message.dataBody;
	console.log(socketData)
	const data = {
		Temperature : socketData[0].environmentTemperature,
		Humidity : socketData[0].environmentHumidity,
		SmokeScope : socketData[0].environmentSmokescope,
		workStatus: socketData[0].deviceWorkStatus,
		securityLevel : socketData[0].securityLevel
	}
	// 温度
	// 如果环境数据所携带的设备ID与散点中的设备ID相同，则将该数据保存到该散点数据中保存并显示
	coordinate.value.map((item : any) => {
		if (message.dataType === item.deviceId){
			item.Temperature = data.Temperature;
			item.Humidity = data.Humidity;
			item.SmokeScope = data.SmokeScope;
			item.workStatus = data.workStatus;
			item.securityLevel = data.securityLevel;
		}
	})
	// 湿度
	// 烟雾浓度
	// 更新视图
	updateSeriesData();
}
</script>

<style>
.page-left{
	width: 300%;
	height: 740px;
;
}
.page-right{
	width: 105%;
	height: 740px;
	margin-left: 205%;
}
.map{
	width: 1170px;
	height: 740px;
}
</style>
